package cn.wolfcode.controller;

import cn.wolfcode.domain.Reply;
import cn.wolfcode.domain.User;
import cn.wolfcode.redis.service.IUserRedisService;
import cn.wolfcode.service.IReplyService;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.utils.JsonResult;
import cn.wolfcode.vo.ReplyVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/tieba")
public class TieBaController {

    @Autowired
    private IReplyService replyService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRedisService userRedisService;


    @RequestMapping("/reply")
    public Object reply(String reply , HttpServletRequest request){
        String token = request.getHeader("token");
        // 以此token去Redis中查询当前登录的用户信息
        User user = userRedisService.getUserByToken(token);
        if (user == null){
            return JsonResult.error(JsonResult.CODE_NOLOGIN,"请先登录在发表",null);
        }

        if (!StringUtils.hasText(reply)){
            return JsonResult.error(JsonResult.CODE_ERROR,"发表内容不能为空",null);
        }

        Reply r = new Reply();
        r.setContent(reply);
        r.setReplyTime(new Date());
        r.setReplyUserId(user.getId());
        r.setUser(user);
        replyService.save(r);
        return JsonResult.success();

    }

    @RequestMapping("/list")
    public Object list(){
        List<Reply> list = replyService.list();
        for (Reply reply : list) {
            reply.setUser(userService.getById(reply.getReplyUserId()));
        }
        return JsonResult.success(list);
    }

    @RequestMapping("/rank")
    public Object rank(){
        List<ReplyVo> list= replyService.rank();
        return JsonResult.success(list);
    }


}
